package cn.ywang.current.demo;

import java.util.concurrent.Semaphore;

/**
 * @author BeatificWang
 * @date 2019/7/30 22:37
 */
public class SemaphoreDemo extends Thread {

	private int num;

	// 限流
	private Semaphore semaphore;

	public SemaphoreDemo(int num, Semaphore semaphore) {
		this.num = num;
		this.semaphore = semaphore;
	}

	@Override
	public void run() {
		try {
			this.semaphore.acquire();
			System.out.println("第" + this.num + "辆车，抢占车位成功");
			Thread.sleep(2000);
			System.out.println("第" + this.num + "辆车开走了");
			this.semaphore.release();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		Semaphore semaphore = new Semaphore(3);
		for (int i = 0; i < 8; i++) {
			new SemaphoreDemo(i, semaphore).start();
		}
	}
}
